/** 
  *@CopyRight(c)2009 company Co.Ltd. 
  *@All right reserved.
  *@module name: App.Base.SystemManage.SystemRolesPermsManage
  *@description:
  *
  *@author: lugj
  *@version: 1.0
  *@date: 2009/07/13
  *@last date: 2009/07/13
  *@history:
    1.
    2.
  *@bugs:
    1. 
    2. 
  *
*/ 

Ext.namespace("App.Base.SystemManage");

//SystemRolesPermsManage Class
App.Base.SystemManage.SystemRolesPermsManage = function(config){
	this.config = config;
	this.MODULE_ID = App.Base.Common.func.generateGlobalUniqueId(this.config, 'SYSROLEPERMMGR');

	this.opCmd = App.Base.common.param.OP_CMD_NONE;
	this.queryCmd = App.Base.common.param.OP_CMD_QUERY;
	this.waitOpLoadMask = new Ext.LoadMask(Ext.getBody(), {msg: "系统正在处理客户端请求，请稍候...", removeMask: false});

	this.roleId = "";
	this.permId = "";

	//
	this.handlerReqSuccess = function(response){
		this.waitOpLoadMask.hide();
		//var result = decodeURIComponent(response.responseText);
		var result = Ext.decode(response.responseText);
		//{returnCode: , msg: );
		
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			//msg: result.returnCode + '：'+ result.msg,
			msg: result.msg,
			icon: (result.returnCode == App.Base.common.param.REQ_SUCCESS) ? Ext.MessageBox.INFO:Ext.MessageBox.ERROR
		});
		
		if (result.returnCode == App.Base.common.param.REQ_SUCCESS)
		{
			this.doLoad();
		}
		//
		this.opCmd = App.Base.common.param.OP_CMD_NONE;
	};

	this.handlerReqFailure = function(){
		this.waitOpLoadMask.hide();
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '服务器请求操作失败，请稍候重试',
			icon: Ext.MessageBox.ERROR
		});	
	};

	this.doRequest = function(config){
		if (config.params != null)
		{			
			this.waitOpLoadMask.show();

			App.Base.Common.func.request({
				method: 'POST',
				url: App.Base.common.param.SYSROLEPERMMGR_OPERATION_DATAURL,
				success: this.handlerReqSuccess,
				failure: this.handlerReqFailure,
				scope: this,
				params: config.params
			});
		}	
	};

	this.doLoad = function(){
		this.gridStore.load({params:{start:0, limit: Ext.getCmp('pagingtbl' + this.MODULE_ID).pageSize}});
	};

	this.handler = function(o){
		if (o.action == App.Base.common.param.BUTTON_ACTION_NONE)
		{
			return;
		}

		var roleIds = '';
		var records = o.rolesGrid.getSelectionModel().getSelections();
		var length = records.length;
		var count = 0;
		for (count = 0; count < length; count++)
		{
			roleIds += records[count].get("roleId");
			if (count < length - 1)
			{
				roleIds += App.Base.common.param.SPLIT_CHARS_VERTICAL_LINE;
			}
		}

		var permIds = "";
		records = o.permsGrid.getSelectionModel().getSelections();
		length = records.length;
		for (count = 0; count < length; count++)
		{
			permIds += records[count].get("permId");
			if (count < length - 1)
			{
				permIds += App.Base.common.param.SPLIT_CHARS_VERTICAL_LINE;
			}
		}

		var params = 'SYS_OP_CMD=' + encodeURIComponent(this.opCmd) 
			+ '&ROLE_ID=' + encodeURIComponent(roleIds)
			+ '&PERM_ID=' + encodeURIComponent(permIds);

		this.doRequest({params: params});
	};

	this.doAdd = function(){
		this.opCmd = App.Base.common.param.OP_CMD_ADD;
		new App.Base.SystemManage.SystemRolesPermsMgrWindow({
			id: this.MODULE_ID,
			title: '分配角色权限',
			iconCls: 'x-menu-systemmanage-key_add',
			opCmd: this.opCmd,
			handler: this.handler,
			scope: this
		}).getMainPanel().show();
	};

	this.doDelete = function(){
		if(!this.grid.selModel.hasSelection()) 
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '请选择删除的角色权限',
				icon: Ext.MessageBox.ERROR
			});					
			return;
		}

		var rolePermIds = "";
		var records = this.grid.getSelectionModel().getSelections();
		var length = records.length;
		for (var count = 0; count < length; count++)
		{
			rolePermIds += records[count].get("rolePermId");
			if (count < length - 1)
			{
				rolePermIds += App.Base.common.param.SPLIT_CHARS_VERTICAL_LINE;
			}
		}

		Ext.MessageBox.show({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '确定要删除选定的角色权限映射关系',
			buttons: Ext.MessageBox.YESNO,
			icon: Ext.MessageBox.QUESTION,
			fn: function(btn){
				if (btn == 'yes')
				{
					this.opCmd = App.Base.common.param.OP_CMD_DELETE;

					var params = 'SYS_OP_CMD=' + encodeURIComponent(this.opCmd) 
						+ '&ROLE_PERM_ID=' + encodeURIComponent(rolePermIds);
					
					this.doRequest({params: params});
				}
			},
			scope: this
		});	
	};

	this.doQuery = function(){
		this.queryCmd = App.Base.common.param.OP_CMD_QUERY;
		this.roleId = Ext.getCmp('roleName' + this.MODULE_ID).getValue();
		this.permId = Ext.getCmp('permName' + this.MODULE_ID).getValue();
		this.gridStore.load({params:{start:0, limit: Ext.getCmp('pagingtbl' + this.MODULE_ID).pageSize}});
	};

	//
    this.gridStore = new Ext.data.Store({
		id: 'gridStore' + this.MODULE_ID,
        proxy: new Ext.data.HttpProxy({url: App.Base.common.param.SYSROLEPERMMGR_GRID_DATAURL}),
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
        }, [
            {name: 'rolePermId'},
            {name: 'roleId'},
            {name: 'permId'},
            {name: 'roleName'},
            {name: 'permName'}
        ]),
		listeners: {
			beforeload: function(store, options){
				options.params.queryCmd = encodeURIComponent(this.queryCmd);
				options.params.roleId = encodeURIComponent(this.roleId);
				options.params.permId = encodeURIComponent(this.permId);
			},
			scope: this
		}
    });

	this.sm = new Ext.grid.CheckboxSelectionModel();//{handleMouseDown: Ext.emptyFn}

	this.grid = new Ext.grid.GridPanel({
		id: 'grid' + this.MODULE_ID,
    	border: false,
		autoScroll: true,
        stripeRows: true,
        loadMask: {msg: '系统正在加载角色权限映射数据，请稍候...'},
        //autoExpandColumn: 'rolePermId' + this.MODULE_ID,
        enableColumnMove: false,
		sm: this.sm,
        cm: new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(),
			{id: 'rolePermId' + this.MODULE_ID, header: '编码', dataIndex: 'rolePermId', hidden: true},
			{id: 'roleName' + this.MODULE_ID, header: '角色名称', dataIndex: 'roleName' , width: 260},
			{header: '权限名称', dataIndex: 'permName' , width: 260},
			this.sm
        ]),
        store: this.gridStore,
		tbar: new Ext.Toolbar({
			border: false,
			items : ['-', {
				text:'<font color="blue">分配权限</font>',
				iconCls: 'x-menu-systemmanage-key_add',
				handler: function(){
					this.doAdd();
				},
				scope: this
			}, '-', {
				text:'<font color="blue">删除</font>',
				iconCls: 'x-menu-systemmanage-key_delete',
				handler: function(){
					this.doDelete();
				},
				scope: this
			}, '-'
			]
		}),
		bbar: new Ext.PagingToolbar({
			id: 'pagingtbl' + this.MODULE_ID,
            pageSize: App.Base.common.param.GRID_PAGE_SIZE_10,
            store: this.gridStore,
            displayInfo: true,
            displayMsg: '共 {2} 条',//'显示第 {0} 条到 {1} 条记录，共 {2} 条',
            emptyMsg: "没有记录",
            plugins: new Ext.ux.PageSizePlugin()
        }),
        viewConfig: {
            //forceFit: true,
            enableRowBody: true,
            getRowClass: function(record, rowIndex, p, ds) {
                var cls = 'white-row';
                switch (rowIndex%2) {
                    case 1:
                        cls = 'red-row'
                        break;
                }
                return cls;
            }
        }
    });

    this.rolesStore = new Ext.data.Store({
		id: 'rolesStore' + this.MODULE_ID,
        proxy: new Ext.data.HttpProxy({url: App.Base.common.param.SYSROLESMGR_GRID_DATAURL}),
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
        }, [
            {name: 'roleId'},
            {name: 'roleParentId'},
            {name: 'roleParentName'},
            {name: 'roleName'},
            {name: 'roleDesc'},
            {name: 'sysHoldFlags'},
            {name: 'state'}
        ]),
		listeners: {
			beforeload: function(store, options){
				options.params.queryCmd = encodeURIComponent(App.Base.common.param.OP_CMD_QUERY);
			},
			scope: this
		}
    });

    this.permsStore = new Ext.data.Store({
		id: 'permsStore' + this.MODULE_ID,
        proxy: new Ext.data.HttpProxy({url: App.Base.common.param.SYSPERMSMGR_GRID_DATAURL}),
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
        }, [
            {name: 'permId'},
            {name: 'permParentId'},
            {name: 'permParentName'},
            {name: 'permName'},
            {name: 'permDesc'},
            {name: 'permCode'},
            {name: 'sysHoldFlags'},
            {name: 'state'}
        ]),
		listeners: {
			beforeload: function(store, options){
				options.params.queryCmd = encodeURIComponent(App.Base.common.param.OP_CMD_QUERY);
			},
			scope: this
		}
    });

    this.form = new Ext.FormPanel({
		autoDestroy: true,
		border: false,
		layout: 'border',
		items: [{
			region:'center',
			frame: true,
			border: false,
			autoScroll: true,
			labelAlign: 'right',
			labelWidth: 128,
			bodyStyle:'padding:5px 5px 5px 0',
			layout: 'border',
			items: [{
				region:'north',
				title : '角色权限分配管理',
				height: 136,
				border: false,
				frame: false,
				autoScroll: true,
				split : true,
				collapsible : true,
				bodyStyle:'padding:18px 5px 5px 0',
				layout: 'form',			
				items :[new Ext.form.ComboBox({
					id: 'roleName' + this.MODULE_ID,
					width: 256,
					fieldLabel: '<font color="red">系统角色</font>',
					emptyText: '请选择角色...',
					//valueNotFoundText: '',
					store: this.rolesStore,
					//value: 0,	
					mode: 'remote',
					//editable: false,
					lazyInit: false,
					//allowBlank: false,
					forceSelection: true,
					selectOnFocus: true,
					queryParam: 'roleName',
					//typeAhead: true,
					minChars: 1,
					loadingText: '正在加载角色数据，请稍候...',
					pageSize: App.Base.common.param.GRID_PAGE_SIZE_5,
					hideTrigger: false,
					triggerAction: 'all',
					valueField: 'roleId',
					displayField: 'roleName',

					listeners: {
						blur: function(combo){
							//combo.setValue(combo.getValue());
						},
						scope: this
					}
				}), 
				new Ext.form.ComboBox({
					id: 'permName' + this.MODULE_ID,
					width: 256,
					fieldLabel: '<font color="red">系统权限</font>',
					emptyText: '请选择权限...',
					//valueNotFoundText: '',
					store: this.permsStore,
					//value: 0,	
					mode: 'remote',
					//editable: false,
					lazyInit: false,
					//allowBlank: false,
					forceSelection: true,
					selectOnFocus: true,
					queryParam: 'permName',
					//typeAhead: true,
					minChars: 1,
					loadingText: '正在加载权限数据，请稍候...',
					pageSize: App.Base.common.param.GRID_PAGE_SIZE_5,
					hideTrigger: false,
					triggerAction: 'all',
					valueField: 'permId',
					displayField: 'permName',

					listeners: {
						blur: function(combo){
							//combo.setValue(combo.getValue());
						},
						scope: this
					}
				}),
				new Ext.Panel({
					bodyStyle:'padding:5px 5px 5px 239px',
					layout:'column',
					items: [{
						width: 86,
						items: [
							new Ext.Button({
								text: '<font color="blue">查 询</font>',
								iconCls: 'x-button-systemmanage-search',
								handler: function(){
									this.doQuery();
								},
								scope: this
							})	
						]
					},{
						width: 128,
						items: [
							new Ext.Button({
								text: '<font color="blue">重 置</font>',
								iconCls: 'x-menu-systemmenusmanage-rset',
								handler: function(){
									this.form.getForm().reset();
								},
								scope: this
							})	
						]
					}]
				})
				]
			},{
				region:'center',
				frame: true,
				border: false,
				autoScroll: true,
				bodyStyle:'padding:5px 5px 5px 0',
				layout: 'fit',
				items: [this.grid]		
			}]
		}]
	});

	this.doLoad();

	//this.form.doLayout();

	//defined methods.
    if((typeof App.Base.SystemManage.SystemRolesPermsManage.SIMULATE_SHARED_METHODS_FLAG) == "undefined")
    {
        App.Base.SystemManage.SystemRolesPermsManage.SIMULATE_SHARED_METHODS_FLAG = true;   

        App.Base.SystemManage.SystemRolesPermsManage.prototype.getMainPanel = function(){   
            return this.form;  
        };
 
        //simulating the class's constructor().
        var __ctor = function(){
        }();
    }
}